
import { _decorator, Component, Node, Camera, Prefab, find, Vec3, tween, rotate, spawn, moveBy, scaleTo, Vec2, NodePool, instantiate, Label, Layers, Scene } from 'cc';
const { ccclass, property } = _decorator;
// 对象名必须与文件一致
import { Common } from './common';


@ccclass('Game')
export class Game extends Component {
	// [1]
	// dummy = '';

	// [2]
	// @property
	// serializableDummy = 0;



	@property({ type: Prefab })
	hitLabelFab = null;
	@property({ type: Prefab })
	enemyFab = null;
	@property({ type: Label })
	enemyCountLabel = null;



	@property({ type: Node })
	leftBoss = null;
	@property({ type: Node })
	rightBoss = null;

	@property({ type: Label })
	score = null;


	private _curPos: Vec3 = new Vec3();
	private _curCameraPos: Vec3 = new Vec3();

	start() {
		// [3]
		// 获取子节点
		this.hero = this.node.getChildByName("hero");

		this.boundary = 6000 / 2;

		this.blackNode = this.node.getChildByName("hero").getComponent("Hero").blackNode;
		this.hitPool = new NodePool("hit");

		// this.canvas = find("Canvas");
		this.canvas = this.node.parent;
		console.log(this.canvas)
		this.allEnemy = [[], []];
		this.updateTime = 0; //每两帧刷新一次
		this.addEnemyList = [];
		this.onAddEnemy = false;
		this.enemyCount = 0; //敌人数量
		this.enemyTotal = 15; //最多敌人数量
		this.addEnemyCurTime = 0;//计算添加敌人时间
		this.addEnemyTime = 3; //5秒添加一个敌人

		Common.playAudio(Common.audioSource.BG, false)
	}


	//随机取的一个范围内的值
	randomN(n) {
		return Math.floor(Math.random() * n);
	}

	//添加敌人
	addEnemy() {

		if (this.enemyCount >= this.enemyTotal) return; //如果敌人数量大于设定数量，即退出
		//随机获取边界范围内任意坐标

		let n = this.randomN(this.boundary) * (Math.random() < 0.5 ? -1 : 1);
		this.addEnemyList.push(n); //插入列队

		this.addEnemySet();//开始添加敌人
	}



	//添加敌人时动画
	addEnemySet() {

		//判断是否正在添加敌人
		if (this.addEnemyList.length < 1 || this.onAddEnemy) return;

		this.onAddEnemy = true;
		let pos = this.addEnemyList[0]; //取的当前敌人的坐标
		this.addEnemyList.shift(); //删除当前任务

		this.node.getChildByName("hero").getPosition(this._curPos)
		// console.log(this.blackNode)
		//设定黑洞坐标
		this.blackNode.setPosition(new Vec3(pos, this._curPos.y + 60, this._curPos.z));
		// console.log(pos)
		//显示黑洞
		this.blackNode.active = true;
		//实例化预制体
		let node = instantiate(this.enemyFab);
		// console.log(node)


		node.parent = this.node;
		node.setPosition(new Vec3(pos, this._curPos.y, this._curPos.z));
		node.getComponent("Enemy").init();

		Common.playAudio(Common.audioSource.enemy_init,true,0.1)

		console.log("addEnemySet", node)
		this.blackNode.active = false;
		this.onAddEnemy = false;
		this.addEnemySet();

		// this.node.setPosition
		//创建动画
		// tween(this.blackNode)
		// .parallel(
		// 	// rotateZ(360)
		//     // this.blackNode.setRotation(0,0,100)
		// )
		// .call(()=>{
		// 	this._curPos.x = pos;	
		//     node.parent = this.node;
		//     // node.setPosition(new Vec2(pos,0));
		// 	node.setPosition(this._curPos);
		//     node.getComponent("Enemy").init();
		// })
		// .by(0.5, {angle:-180})
		// .parallel(
		// 	// this.blackNode.setRotation(0.5,1)
		//     // rotateBy(1,360),			
		//     // scaleTo(0.5,0)
		// )
		// .call(()=>{

		//     this.blackNode.active = false;
		//     this.onAddEnemy = false;
		//     this.addEnemySet();
		// })
		// .start();

	}



	/**
	 * 
	 * @param {number} att 攻击的数值
	 * @param {cc.Vec2} pos 座标
	 */
	showHit(att) {
		let hit = this.hitPool.get();
		//如果获取不到空闲的对象
		if (!hit) {
			hit = instantiate(this.hitLabelFab);
		}
		// // let hit = instantiate(this.hitLabelFab);
		// hit.parent = this.hero; //设定父节点		
		// hit.string=3;

		// let pos = this.hero.getPosition();
		// pos.y += this.hero.height+15;
		// hit.setPosition(pos); //设定坐标
		
		console.log("hit", hit, this.hero.getPosition())
		//加上动画
		//cc.spawn是同时执行
		//往y轴上移动100个像素，并且放大到1.5倍
		// tween(hit)
		// .then(spawn(
		//     moveBy(0.3, new Vec2(0,100)),
		//     scaleTo(0.3, 1.5)
		// ))
		// .then(spawn(
		//     moveBy(0.5, new Vec2(0,100)),
		//     scaleTo(0.5, 1)
		// ))
		// .call(()=>{
		//     //回调涵数,上面两个件事执行完之后，执行这个回调涵数
		//     this.hitPool.put(hit);//把这个节点回收   
		// })
		// .start();


		// tween(hit.node)
		// 	.then(tween().by(0.5, {position:new Vec3(0, 10,0)}).to(0.3, {scale:new Vec3(1.5, 1, 1)}))
		// 	.then(tween().by(0.5, {position:new Vec3(0, 10,0)}).to(0.3, {scale:new Vec3(0.5, 1, 1)}))			
		// 	.call(() => {
		// 		//回调涵数,上面两个件事执行完之后，执行这个回调涵数
		// 		this.hitPool.put(hit);//把这个节点回收   
		// 	})
		// 	.start();


		// this.hitPool.put(hit);//把这个节点回收   


		// this.hitLabel.string = att;

	}

	// true：降序，false：升序
	enemyOrder(order) {
		// b-a:降序；a-b：升序
		return function (a, b) {
			return order ? b.position.x - a.position.x : a.position.x - b.position.x;
		}
	}

	//刷新敌人位置
	updateEnenyList() {

		let arr = this.node.children;
		let node = null;
		this.leftBoss.active = false;
		this.rightBoss.active = false;

		let dis = 480 / 2;

		//过滤已经死亡和主角
		let arrList = [[], []];
		// console.log(arr)
		for (let i = 0, c = arr.length; i < c; i++) {
			node = arr[i];
			// console.log(node)
			if (!node.isDie && node.name != "hero") {
				// console.log(node, this.hero)
				// left
				if (node.getPosition().x < this.hero.getPosition().x) {

					if (node.getPosition().x < this.hero.getPosition().x - dis)
						this.leftBoss.active = true;

					arrList[0].push(node);
				}
				// right
				else {

					if (node.getPosition().x > this.hero.getPosition().x + dis)
						this.rightBoss.active = true;
					arrList[1].push(node);
				}
			}
		}

		this.allEnemy[0] = arrList[0];
		this.allEnemy[1] = arrList[1];

		// 确保每边的首个单位都是离自己最近的那个
		this.allEnemy[0].sort(this.enemyOrder(true));
		this.allEnemy[1].sort(this.enemyOrder(false));
		// console.log(this.allEnemy)
		this.enemyCount = arrList[0].length + arrList[1].length;

		this.enemyCountLabel.string = this.enemyCount;
		// console.log("enemyCountLabel",this.enemyCountLabel)
	}




	// 每帧执行一次
	update(deltaTime: number) {

		//接着，我们每一帧刷新摄像机的位置
		if (this.hero.isDie) return;

		this.updateTime++;
		this.addEnemyCurTime += deltaTime;
		if (this.updateTime >= 2) {
			this.updateTime = 0;
			this.updateEnenyList();
		}


		if (this.addEnemyCurTime >= this.addEnemyTime) {
			this.addEnemyCurTime = 0;
			this.addEnemy();
		}

	}
}



/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
